<template>
  <div class="myAddress">
    <van-nav-bar
      title="我的收货地址"
      left-text="返回"
      :fixed="true"
      left-arrow
      @click-left="back"
    ></van-nav-bar>

    <van-address-list
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="select"
      v-if="isLogin == true"
    />

    <van-empty description="您尚未登录，请先前往登录" v-if="isLogin == false">
      <van-button round type="danger" class="bottom-button" color="#0022ab" @click="toLogin"
        >去登录</van-button
      >
    </van-empty>

    <van-empty
      description="你还没有收货地址哦，赶快去添加一个吧"
      v-if="isLogin == true && list.length == 0"
    ></van-empty>
  </div>
</template>

<script>
export default {
  name: "MyAddress",
  data() {
    return {
      isLogin: true,
      chosenAddressId: "",
      list: [],
    };
  },
  created() {
    this.getAddress();
  },
  methods: {
    back() {
      this.$router.go(-1);
    },
    toLogin() {
      this.$router.push({name:"Login"});
    },
    getAddress() {
      this.axios({
        method: "get",
        url: "/findAddress",
      }).then((result) => {

        if (result.data.code == 700) {
          this.isLogin = false;
          return
        }
        let id = localStorage.getItem("id");
          result.data.result.forEach((item, index) => {
            item.isDefault = Boolean(item.isDefault);
            item.address = `${item.province}${item.city}${item.county}${item.addressDetail}`;
            if (!id) {
              if (item.isDefault) {
                this.chosenAddressId = item.id;
                localStorage.setItem("aid", item.aid);
              } else if (!item.isDefault) {
                if (index == 0) {
                  this.chosenAddressId = item.id;
                  localStorage.setItem("aid", item.aid);
                }
              }
            } else {
              this.chosenAddressId = Number(id);
            }
          });
        this.list = result.data.result;
      });
    },
    onAdd() {
      this.$router.push({name:"NewAddress"});
    },
    onEdit(item) {

      this.$router.push({ name: "NewAddress", query: { aid: item.aid } });
    },
    select(item) {
      localStorage.setItem("aid", item.aid);
      localStorage.setItem("id", item.id);
    },
  },
};
</script>

<style lang="less" scoped>
.myAddress {
  padding-top: 76px;
  .van-nav-bar--fixed{
    padding-top: 30px;
    background-color: #0022ab;
  }
  /deep/.van-nav-bar__title{
    color: #fff;
  }
  /deep/.van-icon{
    color: #fff;
  }
  /deep/.van-nav-bar__text{
    color: #fff;
  }
  /deep/.van-icon-edit{
    color: #969799;
  }
}
</style>